package cn.zjyj.module.zjyj.service.supplier;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.zjyj.module.zjyj.controller.admin.supplier.vo.*;
import cn.zjyj.module.zjyj.dal.dataobject.supplier.SupplierDO;
import cn.zjyj.framework.common.common.pojo.PageResult;
import cn.zjyj.framework.common.common.util.object.BeanUtils;

import cn.zjyj.module.zjyj.dal.mysql.supplier.SupplierMapper;

import static cn.zjyj.framework.common.common.exception.util.ServiceExceptionUtil.exception;
import static cn.zjyj.framework.common.common.util.collection.CollectionUtils.convertList;
import static cn.zjyj.module.zjyj.enums.ErrorCodeConstants.*;

/**
 * 供应商 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class SupplierServiceImpl implements SupplierService {

    @Resource
    private SupplierMapper supplierMapper;

    @Override
    public Long createSupplier(SupplierSaveReqVO createReqVO) {
        // 插入
        SupplierDO supplier = BeanUtils.toBean(createReqVO, SupplierDO.class);
        supplierMapper.insert(supplier);
        // 返回
        return supplier.getId();
    }

    @Override
    public void updateSupplier(SupplierSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplierExists(updateReqVO.getId());
        // 更新
        SupplierDO updateObj = BeanUtils.toBean(updateReqVO, SupplierDO.class);
        supplierMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplier(Long id) {
        // 校验存在
        validateSupplierExists(id);
        // 删除
        supplierMapper.deleteById(id);
    }

    @Override
        public void deleteSupplierListByIds(List<Long> ids) {
        // 校验存在
        validateSupplierExists(ids);
        // 删除
        supplierMapper.deleteByIds(ids);
        }

    private void validateSupplierExists(List<Long> ids) {
        List<SupplierDO> list = supplierMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(SUPPLIER_NOT_EXISTS);
        }
    }

    private void validateSupplierExists(Long id) {
        if (supplierMapper.selectById(id) == null) {
            throw exception(SUPPLIER_NOT_EXISTS);
        }
    }

    @Override
    public SupplierDO getSupplier(Long id) {
        return supplierMapper.selectById(id);
    }

    @Override
    public PageResult<SupplierDO> getSupplierPage(SupplierPageReqVO pageReqVO) {
        return supplierMapper.selectPage(pageReqVO);
    }

}